import 'package:fish_redux/fish_redux.dart';
import 'package:kunlun_gas/app_files.dart';
import 'package:url_launcher/url_launcher.dart';
import 'action.dart';
import 'state.dart';
import 'dart:io';

Effect<AlipayViewState> buildEffect() {
  return combineEffects(<Object, Effect<AlipayViewState>>{
    AlipayViewAction.action: _onAction,
    AlipayViewAction.onHandleUrl: _onHandleUrl,
  });
}

void _onAction(Action action, Context<AlipayViewState> ctx) {}

void _onHandleUrl(Action action, Context<AlipayViewState> ctx) async {
  String url = action.payload;
  if (url.startsWith('alipays://') || url.startsWith('alipay://')) {
    bool isCanLaunch = await canLaunch(url);
    if (!isCanLaunch) {
      int ret = await CommonUtils.showOKCanceltView(
          ctx.context, '未检测到支付宝客户端，请安装后重试。');
      if (ret == 1) {
        if (Platform.isAndroid) {
          launch('https://d.alipay.com');
        } else if (Platform.isIOS)
          launch(
              'https://itunes.apple.com/cn/app/zhi-fu-bao-qian-bao-yu-e-bao/id333206289?mt=8');
      }
    } else {
      launch(url);
      await Future.delayed(Duration(seconds: 3));
      CommonUtils.pushReplaceRoute(ctx.context, RoutePath.chargeResultView,
          arguments: {
            'orderNo': ctx.state.orderNo,
            'transNo': ctx.state.transNo,
          });
    }
  }
}
